﻿using System;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;

namespace Com.Core.Helps
{
    public class HtmlUtils
    {
        public static string MessageBox(string str, int goBack = -1, bool refresh = false)
        {
            string t = $"<script>alert('{str}');history.go({goBack});</script>";
            if (goBack == -1 && refresh)
            {
                t = $"<script>alert('{str}');location.href=document.referrer;</script>";
            }
            return t;
        }

        public static string MessageBox(string str, string url)
        {
            string t = $"<script>alert('{str}');location.href='{url}';</script>";
            return t;
        }

        /// <summary>
        /// 数字转大写汉字
        /// </summary>
        /// <param name="num"></param>
        /// <returns></returns>
        public static string CmycurD(decimal num)
        {
            string str1 = "零壹贰叁肆伍陆柒捌玖";            //0-9所对应的汉字
            string str2 = "万仟佰拾亿仟佰拾万仟佰拾元角分"; //数字位所对应的汉字
            string str5 = "";  //人民币大写金额形式
            int i;    //循环变量
            int j;    //num的值乘以100的字符串长度
            string ch2 = "";    //数字位的汉字读法
            int nzero = 0;  //用来计算连续的零值是几个

            num = Math.Round(Math.Abs(num), 2);    //将num取绝对值并四舍五入取2位小数
            var str4 = ((long)(num * 100)).ToString();
            j = str4.Length;      //找出最高位
            if (j > 15) { return "溢出"; }
            str2 = str2.Substring(15 - j);   //取出对应位数的str2的值。如：200.55,j为5所以str2=佰拾元角分

            //循环取出每一位需要转换的值
            for (i = 0; i < j; i++)
            {
                var str3 = str4.Substring(i, 1);    //从原num值中取出的值
                var temp = Convert.ToInt32(str3);            //从原num值中取出的值
                string ch1;    //数字的汉语读法
                if (i != (j - 3) && i != (j - 7) && i != (j - 11) && i != (j - 15))
                {
                    //当所取位数不为元、万、亿、万亿上的数字时
                    if (str3 == "0")
                    {
                        ch1 = "";
                        ch2 = "";
                        nzero = nzero + 1;
                    }
                    else
                    {
                        if (str3 != "0" && nzero != 0)
                        {
                            ch1 = "零" + str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                        else
                        {
                            ch1 = str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                    }
                }
                else
                {
                    //该位是万亿，亿，万，元位等关键位
                    if (str3 != "0" && nzero != 0)
                    {
                        ch1 = "零" + str1.Substring(temp * 1, 1);
                        ch2 = str2.Substring(i, 1);
                        nzero = 0;
                    }
                    else
                    {
                        if (str3 != "0" && nzero == 0)
                        {
                            ch1 = str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                        else
                        {
                            if (str3 == "0" && nzero >= 3)
                            {
                                ch1 = "";
                                ch2 = "";
                                nzero = nzero + 1;
                            }
                            else
                            {
                                if (j >= 11)
                                {
                                    ch1 = "";
                                    nzero = nzero + 1;
                                }
                                else
                                {
                                    ch1 = "";
                                    ch2 = str2.Substring(i, 1);
                                    nzero = nzero + 1;
                                }
                            }
                        }
                    }
                }
                if (i == (j - 11) || i == (j - 3))
                {
                    //如果该位是亿位或元位，则必须写上
                    ch2 = str2.Substring(i, 1);
                }
                str5 = str5 + ch1 + ch2;

                if (i == j - 1 && str3 == "0")
                {
                    //最后一位（分）为0时，加上“整”
                    str5 = str5 + '整';
                }
            }
            if (num == 0)
            {
                str5 = "零元整";
            }
            return str5.Replace("元", "").Replace("整", "");
        }


        /// <summary>
        /// 移除所有html标签
        /// </summary>
        /// <param name="inputStr">输入字符串</param>
        /// <returns></returns>
        public static string RemoveHtmlTags(string inputStr)
        {
            Regex regex = new Regex(@"<[^>]+>|</[^>]+>");
            return regex.Replace(inputStr, "");
        }

        public static string RemoveBlank(string str)
        {
            Regex regex = new Regex(@"\s");
            return regex.Replace(str, "");
        }

        /// <summary>
        /// 取得HTML中所有图片的 URL。
        /// </summary>
        /// <param name="sHtmlText">HTML代码</param>
        /// <returns>图片的URL列表</returns>
        public static string[] GetHtmlImageUrlList(string sHtmlText)
        {
            // 定义正则表达式用来匹配 img 标签
            Regex regImg = new Regex(@"<img\b[^<>]*?\bsrc[\s\t\r\n]*=[\s\t\r\n]*[""']?[\s\t\r\n]*(?<imgUrl>[^\s\t\r\n""'<>]*)[^<>]*?/?[\s\t\r\n]*>", RegexOptions.IgnoreCase);

            // 搜索匹配的字符串
            MatchCollection matches = regImg.Matches(sHtmlText);

            int i = 0;
            string[] sUrlList = new string[matches.Count];

            // 取得匹配项列表
            foreach (Match match in matches)
                sUrlList[i++] = match.Groups["imgUrl"].Value;

            return sUrlList;
        }

        public static Int64 ToDenaryIp(string ip)
        {
            Int64 int64 = 0;
            string tempIp = ip;
            if (tempIp == null) throw new ArgumentNullException(nameof(tempIp));
            if (tempIp.LastIndexOf(".", StringComparison.Ordinal) > -1)
            {
                string[] iparray = tempIp.Split('.');
                int64 = Int64.Parse(iparray.GetValue(0).ToString()) * 256 * 256 * 256 + Int64.Parse(iparray.GetValue(1).ToString()) * 256 * 256 + Int64.Parse(iparray.GetValue(2).ToString()) * 256 + Int64.Parse(iparray.GetValue(3).ToString()) - 1;
            }
            return int64;
        }
        /// <summary>
        /// /ip十进制
        /// </summary>
        public static Int64 DenaryIp
        {
            get
            {
                Int64 int64 = 0;
                string ip = GetClientIp();
                if (ip.LastIndexOf(".", StringComparison.Ordinal) > -1)
                {
                    string[] iparray = ip.Split('.');
                    int64 = Int64.Parse(iparray.GetValue(0).ToString()) * 256 * 256 * 256 + Int64.Parse(iparray.GetValue(1).ToString()) * 256 * 256 + Int64.Parse(iparray.GetValue(2).ToString()) * 256 + Int64.Parse(iparray.GetValue(3).ToString()) - 1;
                }
                return int64;
            }
        }
        //是否ip格式
        public static bool IsIpAddress(string str1)
        {
            if (string.IsNullOrEmpty(str1) || str1.Length < 7 || str1.Length > 15) return false;
            string regformat = @"^\\d{1,3}[\\.]\\d{1,3}[\\.]\\d{1,3}[\\.]\\d{1,3}$";
            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);
            return regex.IsMatch(str1);
        }

        public static string GetClientIp()
        {
            var result = HttpContext.Current?.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (!string.IsNullOrEmpty(result))
            {
                //可能有代理
                if (result.IndexOf(".", StringComparison.Ordinal) == -1) //没有"."肯定是非IPv4格式
                    result = null;
                else
                {
                    if (result.IndexOf(",", StringComparison.Ordinal) != -1)
                    {
                        //有","，估计多个代理。取第一个不是内网的IP。
                        result = result.Replace(" ", "").Replace("", "");
                        string[] temparyip = result.Split(",;".ToCharArray());
                        foreach (string t in temparyip)
                        {
                            if (IsIpAddress(t)
                                && t.Substring(0, 3) != "10."
                                && t.Substring(0, 7) != "192.168"
                                && t.Substring(0, 7) != "172.16.")
                            {
                                return t; //找到不是内网的地址
                            }
                        }
                    }
                    else if (IsIpAddress(result)) //代理即是IP格式
                        return result;
                    else
                        result = null; //代理中的内容 非IP，取IP
                }
            }
            //string ipAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

            if (string.IsNullOrEmpty(result))
                result = HttpContext.Current?.Request.ServerVariables["REMOTE_ADDR"];
            if (string.IsNullOrEmpty(result))
                result = HttpContext.Current?.Request.UserHostAddress;
            return result;
        }

        /// <summary>
        /// 获取指定长度字符串
        /// </summary>
        /// <param name="stringInput">输入字符串</param>
        /// <param name="stringLength">字符串长度</param>
        /// <param name="adddot">是否加入...</param>
        /// <returns>截取后字符串</returns>
        public static string GetString(string stringInput, int stringLength, bool adddot = false)
        {
            if (stringInput == " " || stringInput == null)
                return " ";
            string tempTitle = " ";
            if (stringInput.Length > stringLength)
                if (adddot)
                    tempTitle = stringInput.Substring(0, stringLength) + "...";
                else
                    tempTitle = stringInput.Substring(0, stringLength);
            else if (stringInput.Length == stringLength)
                tempTitle = stringInput;
            else
            {
                for (int i = 0; i < stringLength - stringInput.Length; i++)
                {
                    tempTitle = stringInput;
                }
            }
            return tempTitle;
        }

        public static string ConvertBoolToCharator(bool str)
        {
            return str ? "是" : "否";
        }

        /// <summary>
        /// HMTL转码
        /// </summary>
        /// <param name="inputStr">需要转码的字符串</param>
        /// <returns>转码后的字符串</returns>
        public static string HtmlEncode(string inputStr)
        {
            if (!string.IsNullOrEmpty(inputStr))
            {
                inputStr = HttpContext.Current.Server.HtmlEncode(inputStr);
                //inputStr = inputStr.Replace("<", "&lt;").Replace(">", "&gt;");
                //inputStr = inputStr.Replace(" ", "&nbsp;");
                inputStr = inputStr.Replace("\n\r", "<br />");
                inputStr = inputStr.Replace("\r\n", "<br />");
                inputStr = inputStr.Replace("\n", "<br />");
                inputStr = inputStr.Replace("\r", "<br />");
                return inputStr;
            }
            return "";
        }

        public static string HtmlDecode(string inputStr)
        {
            if (!string.IsNullOrEmpty(inputStr))
            {
                inputStr = HttpContext.Current.Server.HtmlDecode(inputStr);
                inputStr = inputStr.Replace("<br>", "<br />").Replace("<br />", "\n");
                return inputStr;
            }
            return "";
        }

        /// <summary>
        /// 检查上传文件扩展名
        /// </summary>
        /// <param name="fileName">被检查的文件名</param>
        /// <returns>布尔型</returns>
        public static bool CheckFileExtension(string fileName)
        {
            string fileExtension = Path.GetExtension(fileName);
            if (fileExtension != null)
                fileExtension = fileExtension.ToLower();
            else
                return false;
            string[] restrictExtension = { ".Gif", ".jpg", ".png" };
            return restrictExtension.Any(t => fileExtension == t);
        }

        /// <summary>
        /// 判断是否是移动端（含微信）
        /// </summary>
        /// <returns></returns>
        public static bool IsMobile()
        {
            string agent = HttpContext.Current.Request.UserAgent;
            if (string.IsNullOrEmpty(agent)) return false;
            agent = agent.ToLower();
            return HttpContext.Current.Request.Browser.IsMobileDevice || agent.Contains("iphone") || agent.Contains("ipad") || agent.Contains("android") ||
                   agent.Contains("mobile") || IsWechat();
        }

        public static bool IsWechat()
        {
            string agent = HttpContext.Current.Request.UserAgent;
            return !string.IsNullOrEmpty(agent) && agent.Contains("MicroMessenger");
        }

        /// <summary>
        /// 检测危险字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns>TRUE:OK,FALSE:有问题</returns>
        public static bool CheckInput(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                str = str.ToLower();
                string[] danger = { "<script", "<img", "href", "src", "<form", ".js", ".css" };
                if (danger.Any(item => str.Contains(item)))
                {
                    return false;
                }
            }
            return true;
        }

        public static string RemoveDangerText(string str)
        {
            if (string.IsNullOrEmpty(str)) return null;
            str= Regex.Replace(str, @"<script.*?</script>", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @"<style.*?</style>", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, @".*?.js", "", RegexOptions.IgnoreCase);
            return str;
        }
    }
}
